package com.ly.gen.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.common.core.utils.StringUtils;
import com.ly.gen.entity.GenField;
import com.ly.gen.entity.GenTable;
import com.ly.gen.mapper.OnlineCgformHeadMapper;
import com.ly.gen.service.IGenFieldService;
import com.ly.gen.service.IGenTableService;
import com.ly.gen.utils.GenDbUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 主表-impl
 *
 * @author luoyun
 * @Date: 2025-06-12
 */
@Service("onlCgformHeadServiceImpl1")
@RequiredArgsConstructor
public class GenTableServiceImpl extends ServiceImpl<OnlineCgformHeadMapper, GenTable> implements IGenTableService {

    private final IGenFieldService fieldService;

    @Override
    public R getId(String id) {
        GenTable entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(GenTable entity) {
        List<GenTable> list = this.list(
                new LambdaQueryWrapper<GenTable>()
                        .orderByDesc(GenTable::getCreateTime)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(GenTable entity, Page<GenTable> page) {
        IPage<GenTable> pageList = this.page(
                page,
                new LambdaQueryWrapper<GenTable>()
                        .orderByDesc(GenTable::getCreateTime)
        );
        return R.ok(pageList);
    }

    @Override
    public R add(GenTable entity) {
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(GenTable entity) {
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<GenTable> dto) {
        List<GenTable> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addByTableName(String tbname) {
        //删除已经存在的
        this.remove(
                new LambdaQueryWrapper<GenTable>()
                        .in(GenTable::getTableName, tbname)
        );
        fieldService.remove(
                new LambdaQueryWrapper<GenField>()
                        .in(GenField::getTableName, tbname)
        );
        Map<String, Object> tableInfo = GenDbUtils.getTableByName(tbname);
        GenTable table = new GenTable();
        table.setTableName(tbname.toLowerCase());
        table.setEntityName(StringUtils.toCamelUpperCase(tbname.toLowerCase()));
        table.setTableType(1);
        table.setIsCheckbox("Y");
        table.setIsDbSynch("Y");
        table.setIsTree("N");
        table.setIsPage("Y");
        table.setQueryMode("group");
        table.setTableTxt(ObjUtil.isNotEmpty(tableInfo.get("TABLE_COMMENT")) ? String.valueOf(tableInfo.get("TABLE_COMMENT")) : tbname.toLowerCase());
        table.setTableVersion(1);
        table.setFormTemplate("1");
        table.setCopyType(0);
        table.setIsDesForm("N");
        table.setScroll(1);
        table.setThemeTemplate("normal");
        String id = IdUtil.getSnowflake().nextIdStr();
        table.setId(id);
        JSONObject var4 = new JSONObject();
        var4.put("tableFixedAction", 1);
        var4.put("tableFixedActionType", "right");
        table.setExtConfigJson(var4.toJSONString());
        List<GenField> fieldList = GenDbUtils.getTableFieldByName(tbname);
        fieldList.stream().forEach(n -> n.setCgformHeadId(id));
        table.setCreateBy("-1");
        this.save(table);
        fieldService.saveBatch(fieldList);
        return R.ok("全部导入完成！");
    }
}
